<?php
	class AccountModel extends CI_Model {
		// 表名
		static $adminTable = "admin";
		static $menuTable = "admin_menu";
		static $schoolUserTable = "school_user";
		static $schoolStudentTable = "school_student";
		static $schoolLogTable = "school_log";

	    public function __construct() {
	        parent::__construct();
	    }

	    // 管理员登录
	    public function admin_login($username, $password){
	    	// 根据用户名，获取用户信息
	    	$this->db->where("username", $username);
	    	$query = $this->db->get(self::$adminTable);
	    	$userInfo = $query->row_array();

	    	// password_hash检查密码
	    	if(!$userInfo || !password_verify($password, $userInfo['password']) || $userInfo['is_delete']) return NULL;
	    	return $userInfo;
		}
		
	    public function get_admin_user(){
	    	// 根据用户名，获取用户信息
	    	$this->db->where("id", 1);
	    	$userInfo = $this->db->get(self::$adminTable)->row_array();
	    	return $userInfo;
		}

	    // 学校登录
	    public function school_user_login($schoolId, $username, $password){
	    	// 根据用户名，获取用户信息
	    	$this->db->where("school_id", $schoolId);
	    	$this->db->where("username", $username);
	    	$query = $this->db->get(self::$schoolUserTable);
	    	$userInfo = $query->row_array();

	    	// password_hash检查密码
	    	if(!$userInfo || !password_verify($password, $userInfo['password']) || $userInfo['is_delete']) return NULL;
	    	return $userInfo;
		}
		
		// 学校登录，只获取管理员
		public function school_user_login_only_admin($schoolId, $username, $password){
			// 根据用户名，获取用户信息
			$this->db->where("school_id", $schoolId);
			$this->db->where("username", $username);
			$this->db->where("user_type", USER_TYPE_SCHOOL);
			$query = $this->db->get(self::$schoolUserTable);
			$userInfo = $query->row_array();

			// password_hash检查密码
			if(!$userInfo || !password_verify($password, $userInfo['password']) || $userInfo['is_delete']) return NULL;
			return $userInfo;
		}


	    // 获取用户权限菜单
	    public function get_admin_menu($userType, $roleMenuId = false, $getParentMenu = false){
	    	$where = "1 AND 1";

	    	// 如果没有权限ID，则默认为0
	    	if(!$roleMenuId) $roleMenuId = -1;

	    	// 获取权限菜单
	    	if($userType == USER_TYPE_SUPER_ADMIN) $where .= " AND FIND_IN_SET('{$userType}', `menu_role_type`)";
	    	if($userType == USER_TYPE_SCHOOL) {
	    		$where .= " AND FIND_IN_SET('{$userType}', `menu_role_type`) ";
	    		// 是否读取父级菜单ID
	    		if($getParentMenu) $where .= "AND (`id` IN ({$roleMenuId}))";
	    		else $where .= " AND (`id` IN ({$roleMenuId}) OR `menu_pid` IN ({$roleMenuId}))";
	    	}

	    	//  如果有传菜单ID，就获取指定的某几个菜单
	    	$roleMenuId = trim($roleMenuId, ",");
	    	if($userType == USER_TYPE_TEACHER) $where .= " AND `id` IN ($roleMenuId)";
	    	// echo $where;exit;
	    	$this->db->where($where);
	    	$this->db->order_by('`menu_pid` ASC, `menu_sort` DESC');

	    	$query = $this->db->get(self::$menuTable);
	    	$menuList = $query->result_array();

	    	// 生成菜单结构
	    	$roleMenu = $roleArray = array();
	    	foreach($menuList as $menu) {
	    		$menuId = $menu['id'];
	    		$menuPid = $menu['menu_pid'];
	    		// 如果没有地址跳转，就返回空
	    		$menu['url'] = $menu['menu_url'] ? admin_url($menu['menu_url']) : 'javascript:;';

	    		// 父级菜单
	    		if($menuPid == 0) {
	    			$menu['sub'] = array();
	    			$roleMenu[$menuId] = $menu;
	    		} else {
	    			// 子菜单
	    			$roleMenu[$menuPid]['sub'][] = $menu;
	    		}
	    		// 菜单权限数组
	    		$roleArray[] = $menu['menu_url'];
	    	}

	    	// 返回值
	    	$ret['roleMenu'] = $roleMenu;
	    	$ret['roleArray'] = $roleArray;
	    	return $ret;
	    }

	    // 获取全部权限菜单
	    public function get_admin_menu_all($params = null) {
	    	// 筛选
	    	if(isset($params['userType'])) $this->db->where("menu_role_type", $params['userType']);
	    	if(isset($params['parentId'])) $this->db->where("menu_pid", $params['parentId']);
	    	// 排序
	    	$this->db->order_by('`menu_pid` ASC, `menu_sort` DESC');

	    	$query = $this->db->get(self::$menuTable);
	    	return $query->result_array();
	    }

	    // 根据菜单id，获取子级菜单
	    public function get_sub_menu_by_id($menuId){
	    	$this->db->where("menu_pid", $menuId);
	    	return $this->db->get(self::$menuTable)->result_array();
	    }

	    // 根据菜单id，获取菜单信息
	    public function get_menu_info($menuId, $getField = '') {
	    	$this->db->where("id", $menuId);
	    	$menuInfo = $this->db->get(self::$menuTable)->row_array();

	    	return $menuInfo && $getField ? $menuInfo[$getField] : $menuInfo;
	    }

		// 根据菜单名称，获取菜单信息
		public function get_menu_info_by_name($menuName, $menuPid = 0) {
			$this->db->where("menu_pid", $menuPid);
			$this->db->where('menu_name', $menuName);
			$menuInfo = $this->db->get(self::$menuTable)->row_array();
			return $menuInfo;
		}
	    // // 检查账号密码是否存在
	    // public function check_username_exists($schoolId, $username, $userId, $userType){
	    // 	// 检查管理员登录表
	    // 	$this->db->where("username", $username);
	    // 	if($userType == USER_TYPE_SUPER_ADMIN) $this->db->where("id !=", $userId);
	    // 	$adminInfo = $this->db->get(self::$adminTable)->row_array();
	    // 	if($adminInfo) return $adminInfo;

	    // 	// 检查学校管理员登录表
	    // 	$this->db->reset_query();
	    // 	$this->db->where("username", $username);
	    // 	$this->db->where("school_id", $schoolId);
	    // 	if($userType == USER_TYPE_SCHOOL || $userType == USER_TYPE_TEACHER) $this->db->where("id !=", $userId);
	    // 	return $this->db->get(self::$schoolUserTable)->row_array();
		// }
		
		//检查账号密码是否存在，版本2，同个学校里，admin，user和student表的username唯一，排除已删除（绑定手机端账号没区分教师学生）
	    public function check_username_exists($schoolId, $username, $userId = 0, $userType = ''){
			// 检查学生登录表
			$this->db->where('username', $username);
			$this->db->where("school_id", $schoolId);
			$this->db->where('is_delete', 0);
			if($userType === '') $this->db->where("id !=", $userId);
			$studentInfo = $this->db->get(self::$schoolStudentTable)->row_array();
	    	if($studentInfo) return $studentInfo;

			// 检查管理员登录表
			$this->db->reset_query();
			$this->db->where("username", $username);
			$this->db->where('is_delete', 0);
	    	if($userType == USER_TYPE_SUPER_ADMIN) $this->db->where("id !=", $userId);
	    	$adminInfo = $this->db->get(self::$adminTable)->row_array();
	    	if($adminInfo) return $adminInfo;

	    	// 检查学校管理员登录表
	    	$this->db->reset_query();
	    	$this->db->where("username", $username);
			$this->db->where("school_id", $schoolId);
			$this->db->where('is_delete', 0);
	    	if($userType == USER_TYPE_SCHOOL || $userType == USER_TYPE_TEACHER) $this->db->where("id !=", $userId);
			return $this->db->get(self::$schoolUserTable)->row_array();
		}

		// 允许学校管理员与教师重名，河西中学校长管理员账号跟教师账号一样
	    public function check_username_exists_exclude_admin($schoolId, $username, $userId = 0, $userType = ''){
			// 检查学生登录表
			$this->db->where('username', $username);
			$this->db->where("school_id", $schoolId);
			$this->db->where('is_delete', 0);
			if($userType === '') $this->db->where("id !=", $userId);
			$studentInfo = $this->db->get(self::$schoolStudentTable)->row_array();
			if($studentInfo) return $studentInfo;
			
			// 检查管理员登录表
			$this->db->reset_query();
			$this->db->where("username", $username);
			$this->db->where('is_delete', 0);
	    	if($userType == USER_TYPE_SUPER_ADMIN) $this->db->where("id !=", $userId);
	    	$adminInfo = $this->db->get(self::$adminTable)->row_array();
	    	if($adminInfo) return $adminInfo;

	    	// 检查学校管理员登录表
	    	$this->db->reset_query();
	    	$this->db->where("username", $username);
			$this->db->where("school_id", $schoolId);
			$this->db->where('is_delete', 0);
			$this->db->where('user_type', USER_TYPE_TEACHER);
	    	if($userType == USER_TYPE_SCHOOL || $userType == USER_TYPE_TEACHER) $this->db->where("id !=", $userId);
			return $this->db->get(self::$schoolUserTable)->row_array();
		}

		//检查座位号是否存在
	    public function check_seatno_exists($classId, $seatno, $studentId = 0){
	    	$this->db->where("class_id", $classId);
			$this->db->where("seat_no", $seatno);
			$this->db->where('is_delete', 0);
	    	if($studentId) {
				$this->db->where("id !=", $studentId);
			}
			return $this->db->get(self::$schoolStudentTable)->row_array();
		}

	    // 获取学校登录账号
	    public function get_school_account($schoolId) {
	    	$this->db->where("school_id", $schoolId);
	    	$this->db->where("user_type", USER_TYPE_SCHOOL);
			$this->db->where("is_delete", 0);
	    	$result = $this->db->get(self::$schoolUserTable)->result_array();
	    	return $result;
		}
		
		// 根据菜单menu_url，获取菜单信息
		public function get_menu_by_url($url){
			$this->db->where("menu_url", $url);
			return $this->db->get(self::$menuTable)->row_array();
		}

	    // 获取日志列表
	    public function get_log_list($params = ""){
			$where = "1";
	    	// 分页
	    	if(isset($params['pageStart']) && isset($params['pageSize'])) $this->db->limit($params['pageSize'], $params['pageStart']);
	    	// 读取指定列
	    	if(isset($params['field'])) $this->db->select($params['field']);
	    	// 学校id
			if(isset($params['schoolId'])) $where .= " AND `school_id`='{$params['schoolId']}'";
			// 校区id
			if(isset($params['campusId'])) $where .= " AND `campus_id`='{$params['campusId']}'";
	    	// 关键字筛选
	    	if(isset($params['keyword'])) $where .= " AND (`realname` LIKE '%{$params['keyword']}%' OR `content` LIKE '%{$params['keyword']}%')";
	    	// 用户类型
			if(isset($params['userType'])) $where .= " AND `user_type`='{$params['userType']}'";
			// 操作类型
			if(isset($params['actionType'])) $where .= " AND `action_type`='{$params['actionType']}'";
			if(isset($params['begintime']) && $params['begintime']) $where .= " AND `createtime` >= '{$params['begintime']}'";
			if(isset($params['endtime']) && $params['endtime']) $where .= " AND `createtime` <= '{$params['endtime']}'";
			$this->db->where($where);
			// 排序
			if(isset($params['orderBy'])) {
				$this->db->order_by($params['orderBy']);
			}
	    	// 是否只获取条数
	    	if(isset($params['getRowNumber'])) {
	    		$result = $this->db->count_all_results(self::$schoolLogTable);
	    	} else {
	    		$result = $this->db->get(self::$schoolLogTable)->result_array();	
	    	}
	    	return $result;
		}
		// 保存日志
		public function save_log_action($dataArr) {
			$res = $this->db->insert(self::$schoolLogTable, $dataArr);
			if($res) {
				return true;
			} else {
				return false;
			}
		}
	}